package com.atguigu.app.dws;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.app.func.MyAllWindowFunction;
import com.atguigu.bean.TradeCartAddBean;
import com.atguigu.utils.MyClickHouseUtil;
import com.atguigu.utils.MyKafkaUtil;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;

import java.time.Duration;

public class Dws0204CartAddWindow {
    public static void main(String[] args) throws Exception {

        //1.获取执行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);
        //StreamTableEnvironment tableEnv = StreamTableEnvironment.create(env);
//        tableEnv.getConfig().setIdleStateRetention(Duration.ofSeconds(18*60+5));
        //  状态后端设置
//        env.enableCheckpointing(3000L, CheckpointingMode.EXACTLY_ONCE);
//        env.getCheckpointConfig().setCheckpointTimeout(60 * 1000L);
//        env.getCheckpointConfig().setMinPauseBetweenCheckpoints(3000L);
//        env.getCheckpointConfig().enableExternalizedCheckpoints(
//                CheckpointConfig.ExternalizedCheckpointCleanup.RETAIN_ON_CANCELLATION
//        );
//        env.setRestartStrategy(RestartStrategies.failureRateRestart(
//                10, Time.of(1L, TimeUnit.DAYS), Time.of(3L, TimeUnit.MINUTES)
//        ));
//        env.setStateBackend(new HashMapStateBackend());
//        env.getCheckpointConfig().setCheckpointStorage("hdfs://hadoop102:8020/gmall/ck");
//        System.setProperty("HADOOP_USER_NAME", "atguigu");
        //2.从kafka dwd层读取dwd_cart_info的数据
        DataStreamSource<String> kafkaDS = env.fromSource(MyKafkaUtil.getKafkaSource("dwd_cart_info", "cart_add"), WatermarkStrategy.noWatermarks(), "kafka-source");
        kafkaDS.print();
        //3.转换为JavaBean
        SingleOutputStreamOperator<TradeCartAddBean> tradeCartAddDS = kafkaDS.map(new MapFunction<String, TradeCartAddBean>() {
            @Override
            public TradeCartAddBean map(String s) throws Exception {
                JSONObject jsonObject = JSON.parseObject(s);
                System.out.println("create_time>>>>>" + jsonObject.getString("create_time"));
                return new TradeCartAddBean("", "", 1L, jsonObject.getLong("create_time"));
            }
        });
        //4.提取watermark
        SingleOutputStreamOperator<TradeCartAddBean> tradeCartAddWMDS = tradeCartAddDS.assignTimestampsAndWatermarks(WatermarkStrategy.<TradeCartAddBean>forBoundedOutOfOrderness(Duration.ofSeconds(2)).withTimestampAssigner(new SerializableTimestampAssigner<TradeCartAddBean>() {
            @Override
            public long extractTimestamp(TradeCartAddBean tradeCartAddBean, long l) {
                System.out.println("ts>>>>>" + tradeCartAddBean.getTs());
                return tradeCartAddBean.getTs();
            }
        }));
        //5.开窗 聚合
        SingleOutputStreamOperator<TradeCartAddBean> reduceDS = tradeCartAddWMDS.windowAll(TumblingEventTimeWindows.of(Time.seconds(10))).reduce(new ReduceFunction<TradeCartAddBean>() {
            @Override
            public TradeCartAddBean reduce(TradeCartAddBean tradeCartAddBean, TradeCartAddBean t1) throws Exception {
                tradeCartAddBean.setCartAddUcount(tradeCartAddBean.getCartAddUcount() + t1.getCartAddUcount());
                return tradeCartAddBean;
            }
        }, new MyAllWindowFunction<TradeCartAddBean, TimeWindow>());
        //6.写出
        reduceDS.print("reduceDS>>>>>");
        reduceDS.addSink(MyClickHouseUtil.getSinkFunction("insert into dws_trade_cart_add_window values(?,?,?,?)"));
        env.execute();


    }
}
